package 
{
	import com.zol.basicMain;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import model.pngSaver;
	import org.bytearray.gif.events.GIFPlayerEvent;
	import view.configPanelView;
	import view.playerView;
	
	/**
	 * 这个项目是为了学习air开发搞的
	 * 项目本身希望能将各种东西转化为css sprite
	 * 比如，图片矩阵 => ul>li>bg
	 * 又或者，gif => css+js
	 * 以及，swf => css+js
	 * @author	Meathill
	 * @version	0.1(2011-02-27)
	 */
	public class Main extends basicMain 
	{
		private const _SPACE:int = 10;
		
		private var _saver:pngSaver;
		private var _bmp:Bitmap;
		private var _panel:configPanelView;
		private var _player:playerView;
		
		public function Main():void 
		{
			super();
		}
		
		/************
		 * functions
		 * *********/
		override protected function dataInit(evt:Event = null):void {
			_saver = new pngSaver();
		}
		override protected function displayInit(evt:Event = null):void {
			makeBg();
			
			// 生成操作界面
			_panel = new configPanelView(this, _SPACE, playerView.HEIGHT + (_SPACE << 2));
			_panel.addEventListener(Event.COMPLETE, onLoadComplete);
			_panel.addEventListener(Event.CHANGE, onChange);
			
			// 生成播放器
			_player = new playerView(this, _SPACE, _SPACE);
			_player.addEventListener(GIFPlayerEvent.COMPLETE, onPlayStart);
			_panel.addEventListener(configPanelView.PREVIEW, _player.makeBmp);
			_panel.addEventListener(configPanelView.SAVE, onSave);
			
			onChange();
		}
		private function makeBg():void {
			var _bmpd:BitmapData = new BitmapData(playerView.WIDTH + (_SPACE << 1), 500, true, 0);
			_bmpd.fillRect(new Rectangle(_SPACE, _SPACE, playerView.WIDTH, playerView.HEIGHT), 0xffffffff);
			_bmpd.fillRect(new Rectangle(_SPACE + 50, playerView.HEIGHT + (_SPACE << 1), playerView.WIDTH - 50, _SPACE), 0xff999999);
			
			_bmp = new Bitmap(_bmpd);
			addChild(_bmp);
		}
		private function onLoadComplete(evt:Event):void {
			_player.addMovie(_panel.data, _panel.type);
		}
		private function onPlayStart(evt:Event):void {
			if (evt is GIFPlayerEvent) {
				trace(GIFPlayerEvent(evt).rect.width, GIFPlayerEvent(evt).rect.height);
				_panel.width = GIFPlayerEvent(evt).rect.width;
				_panel.height = GIFPlayerEvent(evt).rect.height;
				onChange();
			}
		}
		private function onChange(evt:Event= null):void {
			_player.itemWidth = _panel.width;
			_player.itemHeight = _panel.height;
			_player.rows = _panel.rows;
			_player.cols = _panel.cols;
			_player.refresh();
		}
		private function onSave(evt:Event):void {
			_saver.save(_player.bmpd);
		}
	}
}